import urllib.request
import json

# 接收一个字符串作为参数
r = urllib.request.urlopen('https://httpbin.org/get')
# 读取response的内容
text = r.read()
# http返回状态码和msg
print(r.status, r.reason)

# 返回的内容是json格式，直接用Load函数加载
obj = json.loads(text)
print(obj)

# r.headers是一个HTTPMessage对象
# print(r.headers)
for k, v in r.headers._headers:
    print(k, ':', v)

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"\
             "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0"\
             "Safari/537.36"

# 添加自定义的头信息
re = urllib.request.Request('https://httpbin.org/user-agent')
re .add_header('User-Agent', UA)

# 接收一个urllib.request.Request对象作为参数
r = urllib.request.urlopen(re)
res = json.load(r)

# 打印出httpbin网站返回信息里的user-agent
print("user-agent: ",res['user-agent'])


auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm="httpbin auth",
                          uri='/basic-auth/yangshuo/123456',
                          user='yangshuo',
                          passwd='123456')
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
r = urllib.request.urlopen('https://httpbin.org')
print(r.read().decode('utf-8'))


# 使用GET参数
params = urllib.parse.urlencode({'spam': 1, 'eggs': 2,'bacan':2})
url = 'https://httpbin.org/get?%s' % params
with urllib.request.urlopen(url) as f:
    print(json.load(f))

# 使用POST方法传递参数
data = urllib.parse.urlencode({'name': 'Bob', 'age': 18})
data = data.encode()
with urllib.request.urlopen("http://httpbin.org/post",data) as f:
    print(json.load(f))

# 使用代理IP请求远程url
proxy_handler = urllib.request.ProxyHandler({
                        'http': '10.254.72.111',
                    })
# proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
opener = urllib.request.build_opener(proxy_handler)
r = opener.open('http://httpbin.org/ip')
print(r.read())